package com.zc.web.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zc.common.utils.DateUtils;
import com.zc.common.utils.StringUtils;
import com.zc.web.domain.TodayPlan;
import com.zc.web.domain.TodayPlanItem;
import com.zc.web.domain.User;
import com.zc.web.mapper.TodayPlanMapper;
import com.zc.web.mapper.UserMapper;
import com.zc.web.service.ITodayPlanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 今日计划Service业务层处理
 *
 * @author zc
 * @date 2025-09-30
 */
@Service
@Slf4j
public class TodayPlanServiceImpl extends ServiceImpl<TodayPlanMapper, TodayPlan> implements ITodayPlanService
{
    @Autowired
    private TodayPlanMapper todayPlanMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 查询今日计划
     *
     * @param id 今日计划主键
     * @return 今日计划
     */
    @Override
    public TodayPlan selectTodayPlanById(Long id)
    {
                return getById(id);
    }

    /**
     * 查询今日计划列表
     *
     * @param todayPlan 今日计划
     * @return 今日计划
     */
    @Override
    public List<TodayPlan> selectTodayPlanList(TodayPlan todayPlan)
    {
        return todayPlanMapper.selectTodayPlanList(todayPlan);
    }

    /**
     * 新增今日计划
     *
     * @param todayPlan 今日计划
     * @return 结果
     */
        @Transactional
    @Override
    public int insertTodayPlan(TodayPlan todayPlan)
    {

           todayPlan.setCreateTime(DateUtils.getNowDate());
            int rows = todayPlanMapper.insertTodayPlan(todayPlan);
            insertTodayPlanItem(todayPlan);
            return rows;
    }

    /**
     * 修改今日计划
     *
     * @param todayPlan 今日计划
     * @return 结果
     */
        @Transactional
    @Override
    public int updateTodayPlan(TodayPlan todayPlan)
    {

                todayPlan.setUpdateTime(DateUtils.getNowDate());
                todayPlanMapper.deleteTodayPlanItemByGoalId(todayPlan.getId());
            insertTodayPlanItem(todayPlan);
                return updateById(todayPlan) == true ? 1 : 0;
    }

    /**
     * 批量删除今日计划
     *
     * @param ids 需要删除的今日计划主键
     * @return 结果
     */
        @Transactional
    @Override
    public int deleteTodayPlanByIds(Long[] ids)
    {
                todayPlanMapper.deleteTodayPlanItemByGoalIds(ids);
                return removeByIds(Arrays.asList(ids)) == true ? 1 : 0;
    }

    /**
     * 删除今日计划信息
     *
     * @param id 今日计划主键
     * @return 结果
     */
        @Transactional
    @Override
    public int deleteTodayPlanById(Long id)
    {
                todayPlanMapper.deleteTodayPlanItemByGoalId(id);
                return removeById(id) == true ? 1 : 0;
    }

        /**
         * 新增今日计划子项明细信息
         *
         * @param todayPlan 今日计划对象
         */
        public void insertTodayPlanItem(TodayPlan todayPlan)
        {
            List<TodayPlanItem> todayPlanItemList = todayPlan.getTodayPlanItemList();
            Long id = todayPlan.getId();
            if (StringUtils.isNotNull(todayPlanItemList))
            {
                List<TodayPlanItem> list = new ArrayList<TodayPlanItem>();
                for (TodayPlanItem todayPlanItem : todayPlanItemList)
                {
                    todayPlanItem.setGoalId(id);
                    list.add(todayPlanItem);
                }
                if (list.size() > 0)
                {
                        todayPlanMapper.batchTodayPlanItem(list);
                }
            }
        }

    /**
     * 检查并处理昨日计划完成情况
     */
    public void processYesterdayPlanCompletion() {
        // 获取所有用户
        List<User> users = userMapper.selectAllUsers();
        log.info("获取当前用户");
        for (User user : users) {
            log.info("开始处理用户：{}的昨日计划完成情况", user.getId());
            boolean yesterdayPlanCompleted = isYesterdayPlanCompleted(user.getId());
            if (!yesterdayPlanCompleted){
                resetUserStreak(user.getId());
            }
        }
    }

    /**
     * 重置用户连击数
     */
    private void resetUserStreak(Long userId) {
        User user = userMapper.selectUserById(userId);

        if (user != null && user.getCurrentStreak() != null && user.getCurrentStreak() > 0) {
            user.setCurrentStreak(0);
            userMapper.updateUser(user);
        }
    }

    /**
     * 查询用户昨天是否完成了今日计划
     * @param userId 用户ID
     * @return true表示完成，false表示未完成
     */
    private boolean isYesterdayPlanCompleted(Long userId) {
        // 构造查询条件
        TodayPlan queryPlan = new TodayPlan();
        queryPlan.setUserId(userId);
        queryPlan.setPlanDate(DateUtils.getYesterday());
        // 查询昨天的计划
        List<TodayPlan> yesterdayPlans = todayPlanMapper.selectTodayPlanList(queryPlan);

        // 如果昨天没有创建计划，则视为未完成
        if (yesterdayPlans == null || yesterdayPlans.isEmpty()) {
            return false;
        }

        // 获取昨天的计划
        TodayPlan yesterdayPlan = yesterdayPlans.get(0);

        // 检查完成数量是否大于0且完成率是否大于0
        if (yesterdayPlan.getCompletionRate() != null && yesterdayPlan.getCompletionRate().compareTo(BigDecimal.ONE) == 0) {
            return true;
        }

        return false;

    }



}